//
//  YFComposeTypeView.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/9/14.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit
import pop

class YFComposeTypeView: UIView {
    
    var completionBlock: ((_ clsName: String?)->())?
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var backBtnCenterXCons: NSLayoutConstraint!
    
    @IBOutlet weak var dismissBtnCenterXCons: NSLayoutConstraint!
    
    @IBOutlet weak var backButton: UIButton!
    
    fileprivate let distance = UIScreen.main.bounds.width / 6
    
    fileprivate let buttonInfo = [["imageName" : "tabbar_compose_idea", "title" : "文字", "clsName" : "YFComposeViewController"],
                                  ["imageName" : "tabbar_compose_photo", "title" : "照片/视频"],
                                  ["imageName" : "tabbar_compose_weibo", "title" : "长微博"],
                                  ["imageName" : "tabbar_compose_lbs", "title" : "签到"],
                                  ["imageName" : "tabbar_compose_review", "title" : "点评"],
                                  ["imageName" : "tabbar_compose_more", "title" : "更多", "actionName" : "clickMore"],
                                  ["imageName" : "tabbar_compose_friend", "title" : "好友圈"],
                                  ["imageName" : "tabbar_compose_wbcamera", "title" : "微博相机"],
                                  ["imageName" : "tabbar_compose_music", "title" : "音乐"],
                                  ["imageName" : "tabbar_compose_shooting", "title" : "拍摄"],
                                  ]
    
    class func composeTypeView()->YFComposeTypeView {
        let nib = UINib(nibName: "YFComposeTypeView", bundle: nil)
        /**
         * 使用xib 需要注意的一点是:
         * 默认的宽高是600 * 600
         * 所以一定要指定frame
         */
        let composeView = nib.instantiate(withOwner: nil, options: nil)[0] as! YFComposeTypeView
        composeView.frame = UIScreen.main.bounds
        composeView.setupUI()
        return composeView
    }
}

fileprivate extension YFComposeTypeView {
    func setupUI() {
        layoutIfNeeded()
        scrollView.backgroundColor = superview?.backgroundColor
        let rect = scrollView.bounds
        
        for i in 0 ..< 2 {
            let view = UIView(frame: rect.offsetBy(dx: CGFloat(i) * bounds.width, dy: 0))
            scrollView.addSubview(view)
            addButtons(view: view, idx: i * 6)
        }
        ///< 设置scrollView的contentSize
        scrollView.contentSize = CGSize(width: 2 * bounds.width, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
    }
    
    func addButtons(view: UIView, idx: Int) {
        
        let count = 6
        
        ///< 第一个循环负责创建按钮
        for i in idx ..< idx + count {
            if i >= buttonInfo.count {
                break
            }
            let info = buttonInfo[i]
            guard let imageName = info["imageName"],
                let title = info["title"] else {
                    continue
            }
            let button = YFComposeTypeButton.composeTypeButton(imageName: imageName, labelText: title)
            view.addSubview(button)
            ///< 添加点击事件
            if let actionName = info["actionName"] {
                let sel = Selector(actionName)
                button.addTarget(self, action: sel, for: .touchUpInside)
            }else {
                button.addTarget(self, action: #selector(tapAction(sender:)), for: .touchUpInside)
            }
            button.clsName = info["clsName"]
        }
        
        ///< 第二个循环负责布局
        for (i, button) in view.subviews.enumerated() {
            
            ///< 准备一些常量
            let buttonSize = CGSize(width: 100, height: 100)
            let margin = (view.bounds.width - 3 * buttonSize.width) * 0.25
            let col = i % 3
            let x = CGFloat(col + 1) * margin + CGFloat(col) * buttonSize.width
            let y = (i > 2) ? view.bounds.height - buttonSize.height : 0
            button.frame = CGRect(x: x, y: y, width: buttonSize.width, height: buttonSize.height)
        }
    }
}


fileprivate extension YFComposeTypeView {
    @objc func tapAction(sender: YFComposeTypeButton) {
        //        guard let clsName = sender.clsName else {
        //            return
        //        }
        //        let cls = NSClassFromString(clsName) as! UIViewController.Type
        //        let vc = cls.init()
        //        let nav = UINavigationController(rootViewController: vc)
        
        ///< 0. 获取是哪一页
        let page = Int(scrollView.contentOffset.y / scrollView.bounds.width)
        let view = scrollView.subviews[page]
        
        for (i, button) in view.subviews.enumerated() {
            let scale = (button == sender) ? 2 : 0.2
            let scaleAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            scaleAnimation?.toValue = NSValue.init(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnimation?.duration = 0.5
            button.pop_add(scaleAnimation, forKey: nil)
            
            let alphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnimation?.toValue = 0.2
            alphaAnimation?.duration = 0.5
            button.pop_add(alphaAnimation, forKey: nil)
            
            if i == 0 {
                alphaAnimation?.completionBlock = { _, _ in
                    self.completionBlock?(sender.clsName)
                }
            }
        }
    }
    
    /**
     * 这里需要注意的一点是:
     * clickMore这里是用的是反射的方法, 这是OC的方法
     * 如果名字不统一的话, 就会报找不到方法的错
     * 所以不能加参数, 如果加了参数的话, 方法名对不上, 就会报找不到方法的错
     */
    @objc func clickMore() {
        backButton.isHidden = false
        backBtnCenterXCons.constant -= distance
        dismissBtnCenterXCons.constant += distance
        
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.3, options: [], animations: {
            self.scrollView.contentOffset = CGPoint(x: self.bounds.width, y: 0)
            self.layoutIfNeeded()
        }, completion: nil)
    }
    
    @IBAction func dismissView(_ sender: UIButton) {
        //        removeFromSuperview()
        dismissButtons()
    }
    
    @IBAction func backAction(_ sender: UIButton) {
        backBtnCenterXCons.constant = 0
        dismissBtnCenterXCons.constant = 0
        
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.3, options: [], animations: {
            self.scrollView.contentOffset = CGPoint(x: 0, y: 0)
            self.layoutIfNeeded()
            self.backButton.alpha = 0
        }, completion: { _ in
            self.backButton.isHidden = true
            self.backButton.alpha = 1
        })
    }
}

extension YFComposeTypeView {
    func show(completion: @escaping (_ clsName: String?)->()) {
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        vc.view.addSubview(self)
        showWithAnimation()
        completionBlock = completion
    }
    
    fileprivate func showWithAnimation() {
        let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        animation.fromValue = 0
        animation.toValue = 1
        animation.duration = 0.25
        pop_add(animation, forKey: nil)
        showButtons()
    }
    
    fileprivate func showButtons() {
        let view = scrollView.subviews[0]
        for (i, button) in view.subviews.enumerated() {
            let animation:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            animation.fromValue = button.center.y + 400
            animation.toValue = button.center.y
            animation.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            button.pop_add(animation, forKey: nil)
        }
    }
    
    fileprivate func dismissButtons() {
        let page = Int(scrollView.contentOffset.x / bounds.size.width)
        let view = scrollView.subviews[page]
        for (i, button) in view.subviews.enumerated().reversed() {
            let animation:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            animation.fromValue = button.center.y
            animation.toValue = button.center.y + 400
            animation.springBounciness = 8
            animation.springSpeed = 8
            animation.beginTime = CACurrentMediaTime() + CFTimeInterval(view.subviews.count - i) * 0.025
            button.pop_add(animation, forKey: nil)
            
            if i == 0 {
                animation.completionBlock = { _, _ in
                    UIView.animate(withDuration: 0.25, animations: {
                        self.alpha = 0
                    }, completion: { (_) in
                        self.removeFromSuperview()
                    })
                }
            }
        }
    }
}

